package com.tdk.mybatisplus.demo.common.config;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.commons.httpclient.DefaultOkHttpClientFactory;
import org.springframework.cloud.commons.httpclient.OkHttpClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author taodingkai
 * @date 2021/8/18 16:48
 */
@Configuration
@ConditionalOnProperty(name = "proxy.enable", havingValue = "true",matchIfMissing = true)
public class FeignProxyConfig {

    @Value("${proxy.host}")
    private String proxyHost;
    @Value("${proxy.port}")
    private Integer proxyPort;
    @Value("#{'${proxy.domains}'.split(',')}")
    private Set<String> domainList;

    @Bean
    public OkHttpClientFactory okHttpClientFactory(OkHttpClient.Builder builder) {
        return new ProxyOkHttpClientFactory(builder);
    }

    class ProxyOkHttpClientFactory extends DefaultOkHttpClientFactory {
        public ProxyOkHttpClientFactory(OkHttpClient.Builder builder) {
            super(builder);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            List<Proxy> proxyList = new ArrayList<>(1);
            proxyList.add(proxy);
            builder.proxySelector(new ProxySelector() {
                @Override
                public List<Proxy> select(URI uri) {
                    if (uri == null || !domainList.contains(uri.getHost())) {
                        return Collections.singletonList(Proxy.NO_PROXY);
                    }

                    return proxyList;
                }

                @Override
                public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
                    // do nothing
                }
            });
        }
    }
}
